package multi_data.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/**
 * B 数据源
 *
 * @author 延晓磊
 * @since 2021年07月28日
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        // 连接工厂
        entityManagerFactoryRef = "bEntityManagerFactory",
        // 事物管理器
        transactionManagerRef = "bTransactionManager",
        // DAO(Repository)所在目录
        basePackages = {"cn.demoncat.b.dao"}
)
public class BDataSourceConfig {

    @Autowired
    @Qualifier("bDataSource")
    private DataSource dataSource;
    @Autowired
    @Qualifier("vendorProperties")
    private Map<String, Object> vendorProperties;

    @Bean("bEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean bEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSource)
                // 实体类所在位置
                .packages("cn.demoncat.b.pojo")
                .persistenceUnit("bPersistenceUnit")
                .properties(vendorProperties)
                .build();
    }

    @Bean(name = "bEntityManager")
    public EntityManager bEntityManager(EntityManagerFactoryBuilder builder) {
        return bEntityManagerFactory(builder).getObject().createEntityManager();
    }

    @Bean("bTransactionManager")
    public PlatformTransactionManager bTransactionManager(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(bEntityManagerFactory(builder).getObject());
    }

}
